package foodmaterial.action;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import foodmaterial.config.ChoiceDataSource;
import foodmaterial.dto.CustomerInfoDto;
import foodmaterial.dto.MealsTypeDto;
import foodmaterial.entity.*;
import foodmaterial.excel.Excel;
import foodmaterial.service.CustomerService;
import foodmaterial.service.InitService;
import foodmaterial.utils.Constants;
import foodmaterial.utils.FileTools;
import foodmaterial.utils.PageUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/customer")
@RestController
@CrossOrigin(allowCredentials = "true")
public class CustomerAction extends BaseAction{

    @Autowired
    private CustomerService service ;

    @Autowired
    private InitService initService ;

    @Autowired
    private Excel excel ;

    @PostMapping("/addRouterInfo")
    @ChoiceDataSource
    public JsonResult<String> addRouterInfo(@RequestBody @Valid RouterInfo routerInfo,
                                            BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        routerInfo.setDb(this.getSysUser().getDb());
        String result = service.addRouterInfo(routerInfo) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "新增配送线路成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyRouterInfo")
    @ChoiceDataSource
    public JsonResult<String> modifyRouterInfo(@RequestBody @Valid RouterInfo routerInfo,
                                               BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        routerInfo.setDb(this.getSysUser().getDb());
        String result = service.modifyRouterInfo(routerInfo) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "修改配送线路成功") :
                JsonResultTool.get(jsonResult,false,result) ;

    }

    @PostMapping("/queryRouterInfo")
    @ChoiceDataSource
    public JsonResult<PageInfo<RouterInfo>> queryRouterInfo(@RequestBody RouterInfo routerInfo) {
        List<RouterInfo> result = null ;
        if (routerInfo.getPageNo() != -1) {
            PageHelper.startPage(routerInfo.getPageNo(), routerInfo.getPageSize());
            result = service.queryRouterInfo(routerInfo);
        } else {
            result = service.queryRouterInfo(getSysUser().getDb());
        }
        PageInfo<RouterInfo> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/addSupplyType")
    @ChoiceDataSource
    public JsonResult<String> addSupplyType(@RequestBody @Valid SupplyType supplyType,
                      BindingResult bindingResult){
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.addSupplyType(supplyType) ;
        return StringUtils.isEmpty(result) ? JsonResultTool.get(jsonResult,true, "新增配送方式成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifySupplyType")
    @ChoiceDataSource
    public JsonResult<String> modifySupplyType(@RequestBody @Valid SupplyType supplyType,
                                                BindingResult bindingResult){
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.modifySupplyType(supplyType) ;
        return StringUtils.isEmpty(result)  ? JsonResultTool.get(jsonResult,true, "修改配送方式成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/querySupplyType")
    @ChoiceDataSource
    public JsonResult<PageInfo<SupplyType>> querySupplyType(@RequestBody SupplyType supplyType) {
        PageHelper.startPage(supplyType.getPageNo(),supplyType.getPageSize()) ;
        List<SupplyType> result = service.querySupplyType(supplyType) ;
        PageInfo<SupplyType> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/addSupplyTeam")
    @ChoiceDataSource
    public JsonResult<String> addSupplyTeam(@RequestBody @Valid SupplyTeam supplyTeam,
                                            BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.addSupplyTeam(supplyTeam) ;
        return StringUtils.isEmpty(result)  ? JsonResultTool.get(jsonResult,true, "新增配送小组成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifySupplyTeam")
    @ChoiceDataSource
    public JsonResult<String> modifySupplyTeam(@RequestBody @Valid SupplyTeam supplyTeam,
                                               BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.modifySupplyTeam(supplyTeam) ;
        return StringUtils.isEmpty(result) ? JsonResultTool.get(jsonResult,true, "修改配送小组成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/querySupplyTeam")
    @ChoiceDataSource
    public JsonResult<PageInfo<SupplyTeam>> querySupplyTeam(@RequestBody SupplyTeam supplyTeam) {
        PageHelper.startPage(supplyTeam.getPageNo(),supplyTeam.getPageSize()) ;
        List<SupplyTeam> result = service.querySupplyTeam(supplyTeam) ;
        PageInfo<SupplyTeam> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/addSupplyArea")
    @ChoiceDataSource
    public JsonResult<String> addSupplyArea(@RequestBody @Valid SupplyArea supplyArea,
                                            BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.addSupplyArea(supplyArea) ;
        return StringUtils.isEmpty(result) ? JsonResultTool.get(jsonResult,true, "新增配送区域成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifySupplyArea")
    @ChoiceDataSource
    public JsonResult<String> modifySupplyArea(@RequestBody @Valid SupplyArea supplyArea,
                                               BindingResult bindingResult){
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.modifySupplyArea(supplyArea) ;
        return StringUtils.isEmpty(result) ? JsonResultTool.get(jsonResult,true, "修改配送区域成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/querySupplyArea")
    @ChoiceDataSource
    public JsonResult<PageInfo<SupplyArea>> querySupplyArea(@RequestBody SupplyArea supplyArea) {
        PageHelper.startPage(supplyArea.getPageNo(),supplyArea.getPageSize()) ;
        List<SupplyArea> result = service.querySupplyArea(supplyArea) ;
        PageInfo<SupplyArea> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/addCustomerInfo")
    @ChoiceDataSource
    public JsonResult<String> addCustomerInfo(@RequestBody @Valid CustomerInfo customerInfo,
                                              BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.addCustomerInfo(customerInfo) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "新增配送客户成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyCustomerInfo")
    @ChoiceDataSource
    public JsonResult<String> modifyCustomerInfo(@RequestBody @Valid CustomerInfo customerInfo,
                                                 BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.modifyCustomerInfo(customerInfo) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "修改配送客户成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyCustomerInfoOrder")
    @ChoiceDataSource
    public JsonResult<String> modifyCustomerInfoOrder(@RequestBody Map<String,List<CustomerInfo>> data) {
        List<CustomerInfo> customerInfos = data.get("customerInfos") ;
        String result = service.modifyCustomerInfoOrder(customerInfos) ;
        return result == null ? new JsonResult(true, "修改客户显示顺序号成功") :
                new JsonResult(false,result) ;
    }

    @PostMapping("/queryCustomerRoot")
    @ChoiceDataSource
    public JsonResult<PageInfo<List<CustomerInfo>>> queryCustomerRoot() {
        PageHelper.startPage(1,Constants.PAGE_SIZE) ;
        List<CustomerInfo> result = service.queryCustomerRoot() ;
        PageInfo<CustomerInfo> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/queryCustomerInfo")
    @ChoiceDataSource
    public JsonResult<PageInfo<CustomerInfo>> queryCustomerInfo(@RequestBody CustomerInfoDto dto) {
        PageHelper.startPage(dto.getPageNo(),dto.getPageSize()) ;
        List<CustomerInfo> result = service.queryCustomerInfo(dto) ;
        PageInfo<CustomerInfo> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/queryCustomerToTeam")
    @ChoiceDataSource
    public JsonResult<PageInfo<MealsType>> queryCustomerToTeam(@RequestBody Map<String,Object> params) {
        PageHelper.startPage((Integer)params.get("pageNo"),(Integer)params.get("pageSize")) ;
        List<MealsType> result = service.queryCustomerToTeam(params) ;
        PageInfo<MealsType> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/queryCustomerInfoByType")
    @ChoiceDataSource
    public JsonResult<List<CustomerInfo>> queryCustomerInfoByType(@RequestBody Map<String,List<String>> params) {
        List<CustomerInfo> result = service.queryCustomerInfoByType(params.get("customerType")) ;
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @PostMapping("/queryCustomerInfoById")
    @ChoiceDataSource
    public JsonResult<CustomerInfo> queryCustomerInfoById(@RequestBody CustomerInfoDto dto) {
        List<CustomerInfo> result = service.queryCustomerInfo(dto) ;
        return result.isEmpty()?
        new JsonResult(false, ResultCode.SUCCESS,null) :
                new JsonResult(true, ResultCode.SUCCESS,result.get(0)) ;
    }

    @GetMapping("/queryDriver")
    @ChoiceDataSource
    public JsonResult<List<String>> queryDriver() {
        List<String> result = service.queryDriver() ;
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @PostMapping("/addMealsType")
    @ChoiceDataSource
    public JsonResult<String> addMealsType(@RequestBody @Valid MealsType mealsType,
                                              BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.addMealsType(mealsType) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "新增餐别成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyMealsType")
    @ChoiceDataSource
    public JsonResult<String> modifyMealsType(@RequestBody @Valid MealsType mealsType,
                                           BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult);
        if (jsonResult.getSuccess() == false) return jsonResult;
        String result = service.modifyMealsType(mealsType) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "修改餐别成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/removeMealsType")
    @ChoiceDataSource
    public JsonResult<String> removeMealsType(@RequestBody MealsType mealsType) {
        int result = service.removeMealsType(mealsType) ;
        return result > 0 ? new JsonResult(true, "删除餐别成功") :
                new JsonResult(false,"删除餐别失败") ;
    }

    @PostMapping("/queryMealsType")
    @ChoiceDataSource
    public JsonResult<PageInfo<MealsType>> queryMealsType(@RequestBody MealsTypeDto dto) {
        PageHelper.startPage(dto.getPageNo(),dto.getPageSize()) ;
        List<MealsType> result = service.queryMealsType(dto) ;
        PageInfo<MealsType> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/addMealsTypeName")
    @ChoiceDataSource
    public JsonResult<String> addMealsTypeName(@RequestBody @Valid MealsTypeName mealsTypeName,
                                               BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult);
        if (jsonResult.getSuccess() == false) return jsonResult;
        String result = service.addMealsTypeName(mealsTypeName) ;
        return StringUtils.isEmpty(result) ? JsonResultTool.get(jsonResult,true, "新增餐别名称成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyMealsTypeName")
    @ChoiceDataSource
    public JsonResult<String> modifyMealsTypeName(@RequestBody @Valid MealsTypeName mealsTypeName,
                                                  BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult);
        if (jsonResult.getSuccess() == false) return jsonResult;
        String result = service.modifyMealsTypeName(mealsTypeName) ;
        return StringUtils.isEmpty(result) ? JsonResultTool.get(jsonResult,true, "修改餐别名称成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyMealsTypeNameOrderAndCalType")
    @ChoiceDataSource
    public JsonResult<String> modifyMealsTypeNameOrderAndCalType(@RequestBody Map<String,List<MealsTypeName>> data) {
        String result = service.modifyMealsTypeNameOrderAndCalType(data.get("orderAndCalType"),getSysUser().getDb()) ;
        return StringUtils.isEmpty(result) ? new JsonResult(true, "修改餐别显示顺序和统计类型成功") :
                new JsonResult(false,result) ;
    }

    @PostMapping("/removeMealsTypeName")
    @ChoiceDataSource
    public JsonResult<String> removeMealsTypeName(@RequestBody MealsTypeName mealsTypeName) {
        int result = service.removeMealsTypeName(mealsTypeName) ;
        return result > 0 ? new JsonResult(true, "删除餐标名称成功") :
                new JsonResult(false,"删除餐标名称失败") ;

    }

    @PostMapping("/queryMealsTypeName")
    @ChoiceDataSource
    public JsonResult<PageInfo<MealsTypeName>> queryMealsTypeName(@RequestBody MealsTypeName mealsTypeName) {
        List<MealsTypeName> result = null ;
        if (mealsTypeName.getPageNo() != -1) {
            PageHelper.startPage(mealsTypeName.getPageNo(), mealsTypeName.getPageSize());
            result = service.queryMealsTypeName(mealsTypeName);
        } else {
            result = service.queryMealsTypeName(getSysUser().getDb());
        }
        PageInfo<MealsTypeName> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @GetMapping("/queryMealsTypeCalName")
    @ChoiceDataSource
    public JsonResult<List<String>> queryMealsTypeCalName() {
        List<String> result = service.queryMealsTypeCalName() ;
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @PostMapping("/modifyCustomerPassword")
    @ChoiceDataSource
    public JsonResult<String> modifyPassword(@RequestBody CustomerInfoDto dto) {
        String result = service.modifyPassword(dto) ;
        return result == null ? new JsonResult(true, "修改密码成功") :
                new JsonResult(false,result) ;
    }

    @PostMapping("/resetCustomerPassword")
    @ChoiceDataSource
    public JsonResult<String> resetPassword(SysUser user) {
        String result = service.resetPassword(user) ;
        return result == null ? new JsonResult(true, "重置密码成功") :
                new JsonResult(false,result) ;
    }

    @PostMapping("/uploadCustomer")
    @ChoiceDataSource
    public JsonResult<String> uploadCustomer(MultipartFile file) throws IOException {
        int pos = file.getOriginalFilename().lastIndexOf('.') ;
        String suffix =file.getOriginalFilename().substring(pos + 1);
        Workbook workbook = null ;
        try {
            workbook = Excel.getWorkbook(file.getInputStream(),suffix) ;
            String result = excel.uploadCustomerExcel(workbook);
            return result == null ? new JsonResult(true, "上传成功") :
                    new JsonResult(false,result) ;
        } finally {
            FileTools.close(workbook);
        }
    }

    @PostMapping("/uploadMealsType")
    @ChoiceDataSource
    public JsonResult<String> uploadMealsType(MultipartFile file) throws IOException {
        int pos = file.getOriginalFilename().lastIndexOf('.') ;
        String suffix =file.getOriginalFilename().substring(pos + 1);
        Workbook workbook = null ;
        try {
            workbook = Excel.getWorkbook(file.getInputStream(),suffix) ;
            String result = excel.uploadCustomerMealsExcel(workbook);
            return result == null ? new JsonResult(true, "上传成功") :
                    new JsonResult(false,result) ;
        } finally {
            FileTools.close(workbook);
        }
    }

    @GetMapping("/downloadCustomer")
    @ChoiceDataSource
    public void downloadCustomer(HttpServletResponse response) throws IOException {
        this.setDownload(response,excel);
        excel.downloadCustomerExcel(
                Constants.EXCEL_CUSTOMER_TEMPLATE, response.getOutputStream());
    }

    @PostMapping("/stopCustomer")
    @ChoiceDataSource
    public JsonResult<String> stopCustomer(@RequestBody CustomerInfo customerInfo) {
        int result = service.stopCustomer(customerInfo);
        return result != 0 ? new JsonResult(true, "维护成功") :
                new JsonResult(false,"维护失败") ;
    }

    @PostMapping("/editCustomerFoodMaterialSupplier")
    @ChoiceDataSource
    public JsonResult<String> editCustomerFoodMaterialSupplier(@RequestBody Map<String,Object> data) {
        String result = service.editCustomerFoodMaterialSupplier(data) ;
        return result == null ? new JsonResult(true, "设置成功") :
                new JsonResult(false,result) ;
    }

    @PostMapping("/queryCustomerFoodMaterialSupplier")
    @ChoiceDataSource
    public JsonResult<PageInfo<CustomerFoodMaterialSupplier>> queryCustomerFoodMaterialSupplier
            (@RequestBody CustomerFoodMaterialSupplier customerFoodMaterialSupplier) {
        PageHelper.startPage(customerFoodMaterialSupplier.getPageNo(),customerFoodMaterialSupplier.getPageSize()) ;
        List<CustomerFoodMaterialSupplier> result = service.queryCustomerFoodMaterialSupplier(customerFoodMaterialSupplier) ;
        PageInfo<CustomerFoodMaterialSupplier> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/uploadCustomerSupplier")
    @ChoiceDataSource
    public JsonResult<String> uploadCustomerSupplier(MultipartFile file) throws IOException {
        int pos = file.getOriginalFilename().lastIndexOf('.') ;
        String suffix =file.getOriginalFilename().substring(pos + 1);
        Workbook workbook = null ;
        try {
            workbook = Excel.getWorkbook(file.getInputStream(),suffix) ;
            String result = excel.uploadCustomerSupplierExcel(workbook,service);
            return result == null ? new JsonResult(true, "上传成功") :
                    new JsonResult(false,result) ;
        } finally {
            FileTools.close(workbook);
            FileTools.close(file.getInputStream());
        }
    }

    @GetMapping("/clearCustomer")
    @ChoiceDataSource
    public JsonResult<String> clearCustomer() {
        String result = service.clearCustomer() ;
        return result == null ? new JsonResult(true,"清理成功"):
                new JsonResult(false,result);
    }

    @GetMapping("/downloadCustomerTemplate")
    @ChoiceDataSource
    public void downloadCustomerTemplate(
            HttpServletResponse response) throws IOException {
        setDownload(response,"customerTemplate.xlsx");
        StringBuilder imageSavePath = new StringBuilder();
        imageSavePath.append(initService.querySysParamsByCode(Constants.EXCEL_TEMPLATE_PATH).getParamValue()) ;
        imageSavePath.append("customerTemplate.xlsx") ;
        ReadImage.readImage(imageSavePath.toString(),response);
    }

    @GetMapping("/downloadCustomerMealsTemplate")
    @ChoiceDataSource
    public void downloadCustomerMealsTemplate(
            HttpServletResponse response) throws IOException {
        setDownload(response,"customerMealsTemplate.xlsx");
        StringBuilder imageSavePath = new StringBuilder();
        imageSavePath.append(initService.querySysParamsByCode(Constants.EXCEL_TEMPLATE_PATH).getParamValue()) ;
        imageSavePath.append("customerMealsTemplate.xlsx") ;
        ReadImage.readImage(imageSavePath.toString(),response);
    }

}
